package com.mdd.front.controller.yangyangLeadingEnterprise;

import com.aliyun.cloudauth20190307.models.DescribeFaceVerifyResponseBody;
import com.mdd.common.aop.NotLogin;
import com.mdd.common.aop.NotPower;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppEnterprise;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppUser;
import com.mdd.common.entity.yangyangLeadingEnterprise.common.JsonReturn;
import com.mdd.common.entity.yangyangLeadingEnterprise.param.*;
import com.mdd.common.enums.ErrorEnum;
import com.mdd.common.util.RedisUtils;
import com.mdd.common.util.ToolUtils;
import com.mdd.common.util.aliyunContrastFaceVerify.DescribeFaceVerify;
import com.mdd.common.util.aliyunContrastFaceVerify.InitFaceVerify;
import com.mdd.common.util.aliyunIdentity.CertNoTwoElementVerificationUtil;
import com.mdd.common.util.aliyunOss.OssUtil;
import com.mdd.front.cache.TokenLoginCache;
import com.mdd.front.service.yangyangLeadingEnterprise.ITAppDicService;
import com.mdd.front.service.yangyangLeadingEnterprise.ITAppEnterpriseService;
import com.mdd.front.service.yangyangLeadingEnterprise.ITAppUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.math3.util.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/app/common")
@Api(tags = "公共方法")
public class CommonController {

    @Value("${aliyun.face.scene-id}")
    private String sceneId;

    @Resource
    ITAppUserService appUserService;

    @Resource
    ITAppDicService appDicService;

    @Resource
    private OssUtil ossUtil;

    @Resource
    ITAppEnterpriseService appEnterpriseService;

    /**
     * 验证用户登录
     * @param param
     * @return
     */
    @NotLogin
    @PostMapping(value = "/checkUserLoginFlag",produces = "application/json; charset=UTF-8")
    @ApiOperation(value="验证用户登录")
    @ResponseBody
    public String checkUserLoginFlag(@RequestBody CommonParam param) {
        Integer userId = param.getUserId();
        if(userId == null) {
            return JsonReturn.fail("必传参数不能为空",40001).toJsonStr();
        }
       Integer userIdData = TokenLoginCache.get();
        if(userIdData!=null && userIdData.equals(userId)){
            TAppUser appUser = appUserService.selectById(userId);
            if(appUser==null || appUser.getId()==null){
                return JsonReturn.fail("用户数据不存在",40002).toJsonStr();
            }
            Date tokenEndTime = appUser.getTokenEndTime();
            if(tokenEndTime==null || tokenEndTime.before(new Date())){
                return JsonReturn.fail("用户登录已过期",40003).toJsonStr();
            }
            return JsonReturn.success().put("appUser",appUser).toJsonStr();
        }
        return JsonReturn.fail("用户未登录！",40004).toJsonStr();
    }

    /**
     * 验证用户是否绑定企业
     * @param param
     * @return
     */
    @NotLogin
    @PostMapping(value = "/checkUserEnterpriseFlag",produces = "application/json; charset=UTF-8")
    @ApiOperation(value="验证用户是否绑定企业")
    @ResponseBody
    public String checkUserEnterpriseFlag(@RequestBody CommonParam param) {
        Integer userId = param.getUserId();
        if(userId == null) {
            return JsonReturn.fail("必传参数不能为空",40001).toJsonStr();
        }
        return appUserService.checkUserEnterpriseFlag(userId);
    }

    /**
     * 字典表根据类型(下拉列表)查询list
     * @param param
     * @return
     */
    @NotLogin
    @PostMapping(value = "/selectDicListByType",produces = "application/json; charset=UTF-8")
    @ApiOperation(value="字典表根据类型(下拉列表)查询list")
    @ResponseBody
    public String selectDicListByType(@RequestBody CommonParam param) {
        String dicType = param.getDicType();
        if(dicType == null) {
            return JsonReturn.fail("必传参数不能为空",40001).toJsonStr();
        }
        return appDicService.selectDicListByType(dicType);
    }


    @PostMapping("/aaa")
    @ApiOperation(value="测试token")
    @ResponseBody
    public String aaa() {
        Integer userId = TokenLoginCache.get();
        if (userId == null || userId <= 0) {
            return JsonReturn.fail(ErrorEnum.TOKEN_INVALID.getMsg(),ErrorEnum.TOKEN_INVALID.getCode()).toJsonStr();
        }
        return JsonReturn.success().put("userId", userId).toJsonStr();
    }

    @NotLogin
    @NotPower
    @ApiIgnore
    @PostMapping("/upload")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        String url = ossUtil.uploadFile(file, "appManagement/uploads/");
        return JsonReturn.success().put("url", url).toJsonStr();
    }

    /**
     * 发送验证码
     * @param param
     * @return
     */
    @NotLogin
    @PostMapping(value = "/sendSms",produces = "application/json; charset=UTF-8")
    @ApiOperation(value="发送验证码")
    @ResponseBody
    public String sendSms(@RequestBody LoginParam param) {
        return appUserService.sendSms(param);
    }


    /**
     * 人脸识别---发起认证请求
     * @param param
     * @return
     */
    @NotLogin
    @PostMapping(value = "/initFaceVerify",produces = "application/json; charset=UTF-8")
    @ApiOperation(value="人脸识别---发起认证请求")
    public String initFaceVerify(@RequestBody MetaInfoParam param) {
        Pair<Boolean, Object> pair = InitFaceVerify.initFaceVerify(getSceneId(), param.getName(), param.getCertNo(), param);
        if(pair.getKey()){
            return JsonReturn.success().put("certifyId",pair.getValue()).toJsonStr();
        }
        return JsonReturn.fail().toJsonStr();
    }

    /**
     * 人脸识别---获取认证结果
     * @param param
     * @return
     */
    @NotLogin
    @PostMapping(value = "/describeFaceVerify",produces = "application/json; charset=UTF-8")
    @ApiOperation(value="人脸识别---获取认证结果")
    public String describeFaceVerify(@RequestBody DescribeFaceVerifyParam param,HttpServletRequest request) {
        String certifyId = param.getCertifyId();
        String token = request.getHeader("token");
        if(token==null || token.isEmpty() || certifyId==null || certifyId.isEmpty()){
            return JsonReturn.fail("必传参数不能为空",40001).toJsonStr();
        }
        TAppUser appUser = appUserService.selectUserByToken(token);
        if(appUser.getId()==null){
            return JsonReturn.fail("token已失效",40002).toJsonStr();
        }
        Pair<Boolean, DescribeFaceVerifyResponseBody.DescribeFaceVerifyResponseBodyResultObject> pair = DescribeFaceVerify.describeFaceVerify(getSceneId(), certifyId);
        if(pair.getKey()){
            DescribeFaceVerifyResponseBody.DescribeFaceVerifyResponseBodyResultObject value = pair.getValue();
            //todo 是否需要对返回结果进行处理
            appUser.setFaceFlag(1);
            appUserService.updateById(appUser);

            return JsonReturn.success().toJsonStr();
        }
        return JsonReturn.fail().toJsonStr();
    }

    @NotLogin
    @PostMapping("/getUserFace")
    @ApiOperation(value="查询用户是否进行实名认证/人脸认证")
    @ResponseBody
    public String getUserFace(HttpServletRequest request) {
        String token = request.getHeader("token");
        if(token==null || token.isEmpty()){
            return JsonReturn.fail("必传参数不能为空",40001).toJsonStr();
        }
        TAppUser appUser = appUserService.selectUserByToken(token);
        if(appUser.getId()==null){
            return JsonReturn.fail("token已失效",40002).toJsonStr();
        }
        return JsonReturn.success()
                .put("realNameFlag",appUser.getRealNameFlag()!=null && appUser.getRealNameFlag()==1?Boolean.TRUE:Boolean.FALSE)
                .put("faceFlag",appUser.getFaceFlag()!=null && appUser.getFaceFlag()==1?Boolean.TRUE:Boolean.FALSE)
                .toJsonStr();
    }

    @NotLogin
    @PostMapping("/certNoTwoElementVerification")
    @ApiOperation(value="实名认证（姓名+身份证号）")
    @ResponseBody
    public String certNoTwoElementVerification(@RequestBody CertNoTwoElementVerificationParam param, HttpServletRequest request){
        String token = request.getHeader("token");
        String name = param.getName();
        String certNo = param.getCertNo();
        if(token==null || token.isEmpty() || name==null || name.isEmpty() || certNo==null || certNo.isEmpty()){
            return JsonReturn.fail("必传参数不能为空",40001).toJsonStr();
        }
        if(!ToolUtils.checkIdCard(certNo)){
            return JsonReturn.fail("身份证号码格式不正确",40002).toJsonStr();
        }
        TAppUser appUser = appUserService.selectUserByToken(token);
        if(appUser.getId()==null){
            return JsonReturn.fail("token已失效",40003).toJsonStr();
        }
        try {
            Pair<Boolean, String> pair = CertNoTwoElementVerificationUtil.certNoTwoElementVerification(name, certNo);
            if(pair.getKey()){
                //保存用户实名信息
                appUser.setRealName(name);
                appUser.setCertNo(certNo);
                appUser.setRealNameFlag(1);
                appUserService.updateById(appUser);
                return JsonReturn.success().put("certNoTwoElementVerificationFlag",true).toJsonStr();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return JsonReturn.success().put("certNoTwoElementVerificationFlag",false).toJsonStr();
    }


    public Long getSceneId(){
        long num = Long.parseLong(sceneId.substring(0, sceneId.length() - 1));
        return num;
    }

}
